﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using Newtonsoft.Json.Linq;

namespace NetCoreCMS.Web.Areas.Admin.Controllers.Finance
{
    public class Apply_ListController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Finance/Apply_List.cshtml";
        protected int totalCount;
        protected int page;
        protected int pageSize;

        protected string keywords = string.Empty;
        public IApplyService _apply { get; set; }
        public IUsersService _users { get; set; }
        Userconfig cfg = null;
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            ChkAdminLevel("apply_list", CMSEnums.ActionEnum.View.ToString()); //检查权限  
            cfg = Common.XMLConfig.Userconfig.loadConfig(_env.ContentRootPath);
        }
        // GET: /admin/apply_list/

        public IActionResult Index()
        {
            this.keywords = Request.Query["keywords"];
            string pagenum = Request.Query["PageNum"];
            if (int.TryParse(pagenum, out this.pageSize))
            {
                if (this.pageSize > 0)
                {
                    Response.Cookies.Append("apply_page_size", this.pageSize.ToString());
                }
            }
            else
            {
                this.pageSize = GetPageSize(10); //每页数量
            }
            ViewBag.Keywords = this.keywords;
            ViewBag.PageNum = this.pageSize.ToString();

            RptBind("where id>0" + CombSqlTxt(keywords), "add_time desc,id desc");
            return View(WEB_VIEW);
        }

        [HttpPost]
        public ActionResult SubmitDelete()
        {
            ChkAdminLevel("apply_list", CMSEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken record = jobject["list"];
            int id;
            foreach (JToken item in record)
            {
                if (int.TryParse(item["id"].ToString(), out id))
                {
                    if (_apply.Delete(id))
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Delete.ToString(), "删除申请" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string Jscript = JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(Jscript);
        }
        //发放
        [HttpPost]
        public ActionResult SubmitSend()
        {
            ChkAdminLevel("apply_list", CMSEnums.ActionEnum.Audit.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            //批量删除
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken record = jobject["list"];
            int id;
            foreach (JToken item in record)
            {
                if (int.TryParse(item["id"].ToString(), out id))
                {
                    var apply = _apply.GetModel(id);
                    if (apply.send_cancel==0)
                    {
                        apply.send_cancel = 1;
                        apply.send_time = DateTime.Now;
                        apply.send_user_id = GetAdminInfo().id;
                        apply.send_point = apply.apply_point * (1-cfg.tixian_fee-cfg.tixian_chongxiao);
                        apply.remark = "发放";
                        _apply.Update(apply);
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Audit.ToString(), "发放成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string result = JscriptMsg("发放" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(result);
        }
        //批量退回
        [HttpPost]
        public ActionResult SubmitCancel()
        {
            ChkAdminLevel("apply_list", CMSEnums.ActionEnum.Audit.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            //批量删除
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken record = jobject["list"];
            int id;
            foreach (JToken item in record)
            {
                if (int.TryParse(item["id"].ToString(), out id))
                {
                    var apply = _apply.GetModel(id);
                    if (apply.send_cancel==0)
                    {
                        apply.send_cancel = 2;
                        apply.cancel_time = DateTime.Now;
                        apply.cancel_user_id = GetAdminInfo().id;
                        apply.remark = "退回";
                        _apply.Update(apply);
                        _users.UpdateField(apply.user_id, "cash_point+=" + apply.apply_point);
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Audit.ToString(), "退回成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string result = JscriptMsg("退回通过" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(result);
        }
        //导出
        public IActionResult SubmitExport()
        {
            ChkAdminLevel("apply_list", CMSEnums.ActionEnum.Audit.ToString()); //检查权限
            return Export();
        }

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and user_id>0");
            }

            return strTemp.ToString();
        }
        #endregion

        #region 数据绑定=================================
        private void RptBind(string _strWhere, string _orderby)
        {
            this.page = 1;
            int.TryParse(Request.Query["page"], out this.page);
            this.page = this.page <= 0 ? 1 : this.page;
            ViewData["list"] = _apply.GetList(this.page, this.pageSize, _strWhere, _orderby, null);
            this.totalCount = _apply.RecordCount(_strWhere);
            string pageUrl = Utils.CombUrlTxt("index", "keywords={0}&page={1}", this.keywords, "__id__");
            ViewBag.PageContent = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 返回每页数量=============================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Request.Cookies["apply_page_size"], out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        #region 封装后-导出、导入Excel.xlsx文件
        public IActionResult Export()
        {
            string dt1 = DateTime.Now.ToString("yyyy-MM-dd/HH:mm:ss.fff");
            string path = _env.WebRootPath;
            ExcelHelper.Export(GetDic(), path, out Tuple<string, string> t);
            string dt2 = DateTime.Now.ToString("yyyy-MM-dd/HH:mm:ss.fff");
            //return Json(new {
            //    msg = "ok",
            //    data = $"开始时间：{dt1},结束时间：{dt2}"
            //});

            return File(t.Item1, t.Item2);
        }

        private Dictionary<string, DataTable> GetDic()
        {
            DataTable dt = new DataTable("申请提现");
            DataColumn dc1 = new DataColumn("序号", Type.GetType("System.String"));
            DataColumn dc2 = new DataColumn("用户名", Type.GetType("System.String"));
            DataColumn dc3 = new DataColumn("姓名", Type.GetType("System.String"));
            DataColumn dc4 = new DataColumn("开户行", Type.GetType("System.String"));
            DataColumn dc5 = new DataColumn("账号", Type.GetType("System.String"));
            DataColumn dc6 = new DataColumn("申请金额", Type.GetType("System.String"));
            DataColumn dc7 = new DataColumn("实发", Type.GetType("System.String"));
            DataColumn dc8 = new DataColumn("申请日期", Type.GetType("System.String"));
            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);
            dt.Columns.Add(dc4);
            dt.Columns.Add(dc5);
            dt.Columns.Add(dc6);
            dt.Columns.Add(dc7);
            dt.Columns.Add(dc8);
            //以上代码完成了DataTable的构架，但是里面是没有任何数据的  
            var apply = _apply.GetList(1, 10000, "where send_cancel=0", "id asc");
            for (int i = 0; i < apply.Count; i++)
            {
                try
                {
                
                var user = _users.GetModel(apply[i].user_id);
                DataRow dr = dt.NewRow();
                dr["序号"] = (i + 1).ToString();
                dr["用户名"] = user.user_name;
                dr["姓名"] = user.nick_name;
                dr["开户行"] = user.bank_name;
                dr["账号"] = user.bank_number;
                dr["申请金额"] = apply[i].apply_point.ToString();
                dr["实发"] = (apply[i].apply_point * (1 - cfg.tixian_fee - cfg.tixian_chongxiao)).ToString();
                dr["申请日期"] = apply[i].add_time.ToString();
                dt.Rows.Add(dr);
                }
                catch (Exception)
                {

                }
            }
            //填充了100000条相同的记录进去  

            var dic = new Dictionary<string, DataTable>();

            dic.Add($"{dt.TableName}", dt);

            return dic;
        }

        [HttpPost]
        public IActionResult Import(IFormFile excelFile)
        {
            string sWebRootFolder = _env.WebRootPath;
            try
            {
                ExcelHelper.Import(excelFile, sWebRootFolder, out string content);
                return Content(content);
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        } 
        #endregion
    }
}
